import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;

public class UdpEchoServer {
    private DatagramSocket socket;
    public UdpEchoServer(int port) throws SocketException {
        socket=new DatagramSocket(port);
    }
    public void start() throws IOException {
        //启动服务器
        System.out.println("服务器启动");
        while (true){
            //循环一次就相当于处理一次请求
            //处理请求的过程通常都是分为三个过程的
            //1.读取请求并解析
            DatagramPacket requestPacket=new DatagramPacket(new byte[4096],4096);
            socket.receive(requestPacket);
            //把读取到的二进制数据转换为字符串
            String request=new String(requestPacket.getData(),0, requestPacket.getLength());
            //2.根据请求计算响应（服务器最关键的步骤）
            String response=process(request);
            //3.把响应返回给客户端
            //根据response构造DatagramPacket，发送给客户端
            DatagramPacket responsePacket=new DatagramPacket(response.getBytes(),response.getBytes().length
                    ,requestPacket.getSocketAddress());
            //需要指定目的ip和目的端口
            socket.send(responsePacket);
        }
    }

    private String process(String request) {
        return request;
    }

    public static void main(String[] args) throws IOException {
        UdpEchoServer server=new UdpEchoServer(9090);
        server.start();
    }
}
